{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "from bertviz import model_view\n",
    "from transformers import AutoTokenizer, AutoModel, utils\n",
    "\n",
    "utils.logging.set_verbosity_error()  # Suppress standard warnings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# NOTE: This code is model-specific\n",
    "\n",
    "model_version = 'bert-base-uncased'\n",
    "sentence_a = \"the rabbit quickly hopped\"\n",
    "sentence_b = \"The turtle slowly crawled\"\n",
    "\n",
    "model = AutoModel.from_pretrained(model_version, output_attentions=True)\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_version)\n",
    "inputs = tokenizer.encode_plus(sentence_a, sentence_b, return_tensors='pt')\n",
    "input_ids = inputs['input_ids']\n",
    "token_type_ids = inputs['token_type_ids'] # token type id is 0 for Sentence A and 1 for Sentence B\n",
    "attention = model(input_ids, token_type_ids=token_type_ids)[-1]\n",
    "sentence_b_start = token_type_ids[0].tolist().index(1) # Sentence B starts at first index of token type id 1\n",
    "token_ids = input_ids[0].tolist() # Batch index 0\n",
    "tokens = tokenizer.convert_ids_to_tokens(token_ids)    \n",
    "model_view(attention, tokens, sentence_b_start)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}